package org.infosec.lc.exercises.ObjectNetworkTransmission.code.castor;

import java.io.IOException;
import java.io.StringReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.Person;

/**
	文件名：CastorUDPReceive.java
	作  者：林超
	时  间：2011-7-20下午02:54:27

	功能描述：接收网络中传输的xml,并还原为Person
	
	pom.xml	:
			
 */
public class CastorUDPReceive implements Runnable{
	private DatagramSocket c_dgSock;
	private DatagramPacket c_dgPack;
	
	{
		try {
			c_dgSock = new DatagramSocket(6000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		check();

		while(true){
			byte[] buf = new byte[1024];
			c_dgPack = new DatagramPacket(buf,0,1024);
			
			try {
				c_dgSock.receive(c_dgPack);
				
				byte[] data = c_dgPack.getData();
				
				System.out.println("Receive data is：" + new String(data,0,c_dgPack.getLength(),"UTF-8"));

				StringReader sr = new StringReader(new String(data,0,c_dgPack.getLength(),"UTF-8"));
				Person person = (Person) Unmarshaller.unmarshal(Person.class, sr);
				
				System.out.println(person.getName());
				System.out.println(person.getCardId().getAddress());
				
			} catch (IOException e) {
				e.printStackTrace();
			} catch (MarshalException e) {
				e.printStackTrace();
			} catch (ValidationException e) {
				e.printStackTrace();
			}
		}
	}
	private void check(){
		if(c_dgSock==null)
			throw new NullPointerException("CastorUDPReceive c_dgSock is null");
	}
	
	public static void main(String[] args) {
		CastorUDPReceive cUdp = new CastorUDPReceive();
		Thread t = new Thread(cUdp);
		t.start();
	}
}

